package com.zhangh.summer.admin.support.aop.tx;

import com.zhangh.summer.admin.support.ds.common.MixedDS;
import com.zhangh.summer.admin.support.ds.common.setting.DsSettingProperties;
import com.zhangh.summer.admin.support.multipleds.DataSourceContextHolder;
import com.zhangh.summer.admin.support.multipleds.MultiDsUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/**
 * @description: 多数据源拦截器
 * @author: zhanghui  zhanghlucky@163.com
 * @create: 2021-03-19 19:48
 **/
@Slf4j
@Aspect
@Component
@Order(9)//优先Transactional 切面之前执行
public class BizServiceAspect {
    @Resource
    private MixedDS mixedDS;
    @Resource
    private DsSettingProperties dsSettingProperties;

    public BizServiceAspect() {

    }

    @Pointcut("execution(* com.zhangh.*.biz.*(..))")
    public void bizPointcut() {

    }
    @Pointcut("execution(* com.zhangh.*.service.*(..))")
    public void servicePointcut() {

    }

    @Before("bizPointcut() || servicePointcut() ")
    public void doBefore(JoinPoint joinPoint) {
        MethodSignature joinPointObject = (MethodSignature) joinPoint.getSignature();
        Method method = joinPointObject.getMethod();
        boolean flag = method.isAnnotationPresent(MultiDs.class);
        if (!flag) {
            String defaultDsType = MultiDsUtil.getDsType(dsSettingProperties.getDefaultDsName());
            String dsType=DataSourceContextHolder.getDataSourceType();
            if (null==dsType){
                log.debug("统一使用默认数据源 ");
                this.mixedDS.mysql().ds();
            }else{
                if (!dsType.equals(defaultDsType)){
                    log.info("数据源{}切换到默认数据源{}",dsType,defaultDsType);
                    this.mixedDS.mysql().ds();
                }
                //使用的默认数据源，不做处理
            }
        }
    }
}

